iT邦幫忙

0

[JavaScript學習筆記] - undefined、null

  • 分享至 

  • xImage
  •  

undefined 是 代表「尚未賦值」或「沒有定義」。當程式預期要取得某個值,但該值不存在或尚未產生時,就會回傳

常見的 4 種出現時機

  1. 變數已宣告,但尚未賦值
let name;
console.log(name); // 輸出: undefined
console.log(typeof name); // 輸出: 型別undefined
  1. 函式沒有明確的 return
function sayHello() {
  console.log("嗨");
}
console.log(sayHello()); // 輸出: undefined
  1. 物件中存取不存在的屬性
const person = { age: 20 };
console.log(person.name); // 輸出: undefined
  1. 函式呼叫時,遺漏了傳入的參數
function multiply(a, b) {
  console.log(b); // 輸出: undefined
}
multiply(5);

null
null 是有被賦予值,是開發使用者故意告知為空值

let b = 1;
let c = 2;
c = null; //原本c是有值的,使用null將記憶體清除
console.log(c);
//輸出null

圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言